<template>
  <tiny-row :flex="true" justify="center">
    <tiny-col :span="2" class="first">
      <div class="user-info">
        <div class="base-info">
          <img src="../../public/vite.svg" alt="头像" width="60" height="60">
          <div style="display: flex;flex-direction: column;margin-left:10px;font-size:14px;">
            <span>{{ author.nickname }}</span>
            <span>2023-06-06</span>
          </div>
        </div>
        <div class="content-info">
          <div>
            <span>{{ author.articleNum }}</span>
            <span>文章数</span>
          </div>
          <div>
            <span>{{ author.postNum }}</span>
            <span>帖子数</span>
          </div>
          <!--          <div>
                      <span>{{ author.fanNum }}</span>
                      <span>粉丝量</span>
                    </div>-->
        </div>
        <hr/>
        <div v-show="false" class="operation">
          <tiny-button size="small">私聊</tiny-button>
          <tiny-button size="small">关注</tiny-button>
        </div>
      </div>
      <div class="interest-tag">
        <div style="margin-bottom:10px;">
          <span style="font-weight:bold;font-size:14px;">兴趣标签</span>
        </div>
        <div class="tag-list">
          <tiny-tag v-for="tag in author.tagList" :key="tag.id">
            {{ tag.name }}
          </tiny-tag>
        </div>
      </div>
      <div class="article-recommend">
        <div style="margin-bottom: 10px;">
          <span style="font-weight:bold;font-size:14px;">相关推荐</span>
        </div>
        <div class="recommend-article" v-for="article in recommendArticleList" :key="article.id" @click="toArticleDetail(article.id)">
          <div class="top">
            <span style="font-size:16px" v-if="article.title.length > 10">{{ article.title.substring(0, 10) }}...</span>
            <span style="font-size:16px" v-else>{{ article.title }}</span>
          </div>
          <div class="desc" v-if="article.description.length > 22">{{ article.description.substring(0, 22) }}...</div>
          <div class="desc" v-else>{{ article.description }} </div>
        </div>
      </div>
      <!--<div class="article-catalog">-->
      <!--  <u-anchor style="position: fixed" container="#content"></u-anchor>-->
      <!--</div>-->
    </tiny-col>

    <tiny-col :span="10" style="width:80%">
      <div class="right">
        <div class="detail">
          <div class="title">{{ articleDetail.title }}</div>
          <div class="base">
            <div class="type">
              <div class="type__content">
                <span v-if="articleDetail.type === 0">原创</span>
                <span v-else>转载</span>
              </div>
            </div>
            <div class="info">
              <div class="article-status">
                <span style="color:#555666">{{ articleDetail.author }}</span>
                <div style="margin-left:15px;display: flex;align-items: center">
                  <IconTime theme="filled" size="20" fill="#999aaa" :strokeWidth="2"/>
                  <span style="margin-left:3px;">于 {{ articleDetail.createTime }} 发布</span>
                </div>
                <div style="margin-left:15px;display: flex;align-items: center">
                  <preview-open theme="filled" size="24" fill="#999aaa" :strokeWidth="2"/>
                  <span style="margin-left:3px;">{{ articleDetail.accessNumber }}</span>
                </div>
                <div style="margin-left:15px;display: flex;align-items: center">
                  <div class="collect-status"
                       v-if="!collectFlag">
                    <collection-files theme="filled" size="20" fill="#999aaa" :strokeWidth="2"/>
                    <span style="margin-left:3px;">收藏</span>
                  </div>
                  <div class="collect-status" v-else>
                    <collection-files theme="filled" size="20" fill="#5e7ce0" :strokeWidth="2"/>
                    <span style="margin-left:3px;">已收藏</span>
                  </div>

                </div>
              </div>
              <div class="article-tag">
                <span style="color:#999aaa;">文章标签：</span>
                <tiny-tag v-for="tag in articleDetail.tagList" :key="tag.id" type="success">
                  {{ tag.name }}
                </tiny-tag>
              </div>
            </div>
          </div>
          <div class="content" id="content">
            <Editor
                style=""
                v-model="articleDetail.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleEditorCreated"
            />
          </div>
        </div>
        <div class="comment-header">
          <span style="display: flex;align-items: center;cursor: pointer" @click="openComment">
            <span v-if="newComment.total > 0">{{ newComment.total }}条评论</span>
            <span v-else>0条评论</span>
            <right theme="filled" size="24" fill="#333" :strokeWidth="2"/>
          </span>
          <div v-if="newCommentFlag">
            <img v-if="newComment.avatar" :src="newComment.avatar" alt="头像" width="25" height="25">
            <span style="margin-left:5px;color:#777888;cursor: pointer;font-size:14px;">{{ newComment.nickname }}</span>
            <tiny-tag v-if="newComment.nickname" type="danger" size="mini" style="margin:0 10px;">新评</tiny-tag>
            <span>{{ newComment.content }}</span>
          </div>
          <tiny-button type="primary" plain style="margin-left:auto" @click="openComment">写评论</tiny-button>
        </div>
        <div class="comment-list scale-up-ver-bottom" v-if="commentFlag">
          <u-comment
              page
              :config="config"
              relative-time
              @submit="submit"
              @like="like"
          >
          </u-comment>
        </div>
      </div>
    </tiny-col>
  </tiny-row>


  <!-- 点赞和收藏 -->
  <div class="user-behavior">
    <tiny-floatbar style="display: flex;flex-direction: column;padding:6px">
      <good-two @click="starOrCollArticle(true)" v-if="starFlag" theme="filled" size="24" fill="#5e7ce0"
                :strokeWidth="2"/>
      <good-two @click="starOrCollArticle(true)" v-else theme="filled" size="24" fill="#999aaa" :strokeWidth="2"/>
      <file-collection @click="starOrCollArticle(false)" v-if="collectFlag" theme="filled" size="24" fill="#5e7ce0"
                       :strokeWidth="2" style="margin-top:10px"/>
      <file-collection @click="starOrCollArticle(false)" v-else theme="filled" size="24" fill="#999aaa" :strokeWidth="2"
                       style="margin-top:10px"/>
    </tiny-floatbar>
  </div>


</template>

<script setup>
import {
  Button as TinyButton,
  Col as TinyCol,
  Floatbar as TinyFloatbar,
  Modal,
  Row as TinyRow,
  Tag as TinyTag
} from '@opentiny/vue'
import {onUnmounted, ref, shallowRef} from 'vue'
import {CollectionFiles, FileCollection, GoodTwo, PreviewOpen, Right, Time as IconTime} from '@icon-park/vue-next'
import {useRoute, useRouter} from 'vue-router'
import emoji from "../utils/emoji.js";
import {dayjs, UAnchor} from 'undraw-ui'
import request from "../utils/request.js";
import {userName} from "../config/index.js";
import {Editor} from "@wangeditor/editor-for-vue";
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'


const route = useRoute()
const router = useRouter()
const articleId = route.params.articleId
const id = ref('preview-only');
const articleDetail = ref({})
const scrollElement = document.documentElement;
const newComment = ref({})
const commentFlag = ref(false)
const newCommentFlag = ref(true)
const config = ref({
  user: {
    id: 0,
    username: '',
    avatar: '',
    // 评论id数组 根据用户uid来获取对应点赞评论id,然后加入到数组中返回
    // likeIds: [1, 2, 3],
  },
  emoji: emoji,
  comments: [],
  total: 10
})
let temp_id = 100
const recommendArticleList = ref([])
const currentUser = localStorage.getItem(userName) ? JSON.parse(localStorage.getItem(userName)) : null
const author = ref({})
const pageNum = ref(1)
const pageSize = ref(15)
const seconds = ref(0)
let collectFlag = ref(false)
let starFlag = ref(false)
const editorRef = shallowRef()
const editorConfig = {
  readOnly: true,
  autoFocus: false
}
const mode = 'default' // 或 ‘simple’

// 跳转文章详细页
const toArticleDetail = (id) => {
  const {href} = router.resolve( `/article/detail/${id}`)
  window.open(href, '_blank')
}

// 查询文章的相关推荐
const queryRecommendList = () => {
  request.get(`/api/contents/articles/recommend/${articleId}`).then(res => {
    if (res.code === 1) {
      recommendArticleList.value = res.data
    }
  })
}
queryRecommendList()

// 编辑器创建
const handleEditorCreated = (editor) => {
  editorRef.value = editor
  editorRef.value.highlight = hljs
}

// 提交评论事件
const submit = ({content, parentId, files, finish, reply}) => {
  let str = '提交评论:' + content + ';\t父id: ' + parentId + ';\t被回复评论:'
  // console.log(str, reply)

  temp_id++
  const comment = {
    id: temp_id,
    parentId: parentId,
    uid: config.value.user.id,
    content: content,
    likes: 0,
    createTime: dayjs().subtract(5, 'seconds').toString(),
    user: {
      username: config.value.user.username,
      avatar: config.value.user.avatar,
      // homeLink: `/${(temp_id)}`
    },
    reply: null
  }
  // 保存参数 默认回复的文章
  let param = {
    articleId,
    content: comment.content,
    userId: config.value.user.id,
    replyId: articleId,
    replyType: 0
  }
  if (parentId) { // 回复的评论
    const rep = comment.content.match(/<[^>]*>([^<]*)$/)
    param.replyType = 1
    param.content = rep[1].trim()
    // param.parentId = articleId
    param.replyId = reply ? reply.uid : null
    param.parentId = parentId
  }


  setTimeout(() => {
    finish(comment)
    // 保存评论
    request.post('/api/comments/articles', param).then(res => {
      if (res.code === 1) {
        Modal.message({message: '评论成功', status: 'success'})
      }
    })

  }, 200)
}

// todo 点赞按钮事件 将评论id返回后端判断是否点赞，然后在处理点赞状态(需要第三张表)
const like = (id, finish, a, b) => {
  setTimeout(() => {
    finish()
  }, 200)
}

// 打开评论框
const openComment = () => {
  commentFlag.value = !commentFlag.value
  newCommentFlag.value = !newCommentFlag.value
}

// 查询评论
const queryArticleComment = () => {
  const temp = {
    articleId,
    pageParam: {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
  }
  request.post('/api/comments/articles/page', temp).then(res => {
    if (res.code === 1) {
      config.value.user.id = currentUser.id
      config.value.user.username = currentUser.nickname
      config.value.user.avatar = currentUser.avatar
      // 统计当前用户的点赞
      config.value.user.likeIds = res.data.records.map(v => {
        if ((currentUser.id === v.userId) && (v.starNum > 0)) {
          return v.id
        }
      })

      // 处理评论文章的评论
      let tempComments = []
      res.data.records.forEach(comment => {
        let tempComment = {
          user: {
            username: '',
            avatar: '',
            homeLink: ''
          }
        }
        if (comment.replyType === 0) { // 评论文章
          tempComment.id = comment.id
          tempComment.parentId = null
          tempComment.uid = comment.userId
          tempComment.content = comment.content
          tempComment.createTime = comment.createTime.split(' ')[0]
          tempComment.likes = comment.starNum
          tempComment.user.username = comment.nickname
          tempComment.user.avatar = comment.avatar
          tempComment.user.homeLink = '/1'

          tempComments.push(tempComment)
        }
      })

      // 处理回复
      const childrenComments = res.data.records.filter(v => v.replyType === 1) // 取出回复评论
      tempComments.forEach(comment => { // 遍历评论
        comment.reply = {
          total: 0,
          list: [],
        }
        childrenComments.forEach(child => {
          if (child.parentId === comment.id) {
            let tempComment = {
              user: {
                username: '',
                avatar: '',
                homeLink: ''
              }
            }
            tempComment.id = child.id
            tempComment.parentId = child.parentId
            tempComment.uid = child.userId
            tempComment.createTime = child.createTime.split(' ')[0]
            tempComment.likes = child.starNum
            tempComment.user.username = child.nickname
            tempComment.user.avatar = child.avatar
            tempComment.user.homeLink = '/1'

            if (child.replyId === comment.uid) {
              tempComment.content = child.content
            } else {
              const children = childrenComments.find(v => v.userId === child.replyId)
              tempComment.content = "回复 <span style=\"color: var(--u-color-success-dark-2);\">@ " + children.nickname + ":</span>" + child.content
            }

            comment.reply.list.push(tempComment)
          }
        })
        comment.reply.total = comment.reply.list.length
      })
      config.value.comments = tempComments

      // 添加新评
      newComment.value.avatar = tempComments[0].user.avatar
      newComment.value.nickname = tempComments[0].user.username
      newComment.value.homeLink = tempComments[0].user.homeLink
      newComment.value.content = tempComments[0].content
      let total = 0
      tempComments.forEach(c => {
        total += 1
        if (c.reply.total > 0) {
          total += c.reply.total
        }
      })
      newComment.value.total = total
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryArticleComment()

// 查询文章作者
const queryArticleAuthor = () => {
  request.get(`/api/contents/articles/author/${articleId}`).then(res => {
    if (res.code === 1) {
      author.value = res.data
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryArticleAuthor()

// 查询文章和当前用户的状态
const queryArticleAndUserStatus = () => {
  request.get(`/api/contents/articles/${articleId}/${currentUser.id}`).then(res => {
    if (res.code === 1) {
      articleDetail.value = res.data
      document.title = res.data.title
      if (res.data.collectStatus !== null) {
        collectFlag.value = res.data.collectStatus === 1
      } else {
        collectFlag.value = false
      }
      if (res.data.starStatus !== null) {
        starFlag.value = res.data.starStatus === 1
      } else {
        starFlag.value = false
      }
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryArticleAndUserStatus()

// 点赞或收藏文章
const starOrCollArticle = (flag) => {
  if (flag) { // 点赞操作
    starFlag.value = !starFlag.value
  } else {
    collectFlag.value = !collectFlag.value
  }
  let starStatus = starFlag.value ? 1 : 0
  let collectStatus = collectFlag.value ? 1 : 0
  const param = {
    articleId,
    userId: currentUser.id,
    starStatus,
    collectStatus
  }
  request.post('/api/contents/articles/users/starOrColl', param).then(res => {
    if (res.code !== 1) {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}

// 定义定时器
const timer = () => {
  setInterval(() => {
    seconds.value++
  }, 1000)
}
timer()

onUnmounted(() => {
  clearInterval(timer)
  if (currentUser) {
    if (seconds.value >= 2) {
      const tmp = {
        articleId: Number(articleId),
        userId: currentUser.id,
        collectStatus: collectFlag.value ? 1 : 0,
        starStatus: starFlag.value ? 1 : 0,
        commentStatus: 0, // 统一传未评论，在后端查询评论列表判断是否评论
      }
      request.post('/api/contents/articles/users', tmp).then(res => {
        if (res.code !== 1)
          Modal.message({message: res.message, status: 'error'})
      })
    }
  }
})

</script>

<style lang="less" scoped>
.article-catalog {
  border: 1px solid #ccc;
  flex: 1;

  .u-anchor {
    position: relative;
    width: inherit;
  }
}

.collect-status:hover {
  cursor: pointer;
}

.collect-status {
  display: flex;
  align-items: center;
}

.first {
  position: sticky;
  top: 0;
}

.article-recommend {
  margin-top: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px;
}

.recommend-article {
  .top:hover {
    cursor: pointer;
    color: #5E7CE0;
  }
  .desc {
    color: #949494;
    font-size: 14px;
    cursor: pointer;
  }
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.comment-list {
  border-left: 1px solid #ddd;
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  padding: 10px;
}

.comment-header {
  div {
    img {
      border-radius: 100px;
      cursor: pointer;
    }

    display: flex;
    align-items: center;
    margin-left: 20px;
  }

  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-top: 20px;
  padding: 10px;
}

.user-behavior {
  cursor: pointer;
}

.detail {
  .content {
    margin-top: 25px;
  }

  .base {
    .info {
      .article-tag {
        .tiny-tag {
          margin-right: 10px;
        }

        margin-top: 10px;
      }

      .article-status {
        span {
          color: #999aaa;
        }

        display: flex;
        align-items: center;
      }

      margin-left: 10px;
    }

    .type {
      width: 50px;
      height: 30px;
      background: #b8ddb0;
      position: relative;
      transform: skewY(-10deg);
      border: 1px solid #fff;
      box-sizing: border-box;
      transition: all 0.3s;

      .type__content {
        color: #fff;
        text-align: center;
        line-height: 30px;
      }
    }

    border-radius: 5px;
    background-color: #f8f8f8;
    margin-top: 15px;
    display: flex;
    padding-bottom: 5px;
  }

  .title {
    font-size: 28px;
    font-weight: bold;
  }

  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px;
}

.right {
  width: 90%;
}

.interest-tag {
  .tag-list {
    .tiny-tag:hover {
      background-color: #fff;
      color: black;
    }

    .tiny-tag {
      cursor: pointer;
      margin: 0 10px 10px 0;
    }
  }

  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px;
  margin-top: 15px;
}

.user-info {
  .operation {
    text-align: center;
  }

  .content-info {
    div {
      span:last-child {
        color: #999aaa;
      }

      display: flex;
      flex-direction: column;
      text-align: center;
    }

    display: flex;
    align-items: center;
    justify-content: space-around;
    margin-top: 20px;
  }

  .base-info {
    img {
      border-radius: 100px;
    }

    display: flex;
    align-items: center;
  }

  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px;
}

.bottom {
  button {
    appearance: none;
    background-color: transparent;
    border: 0.125em solid #1A1A1A;
    border-radius: 0.9375em;
    box-sizing: border-box;
    color: #3B3B3B;
    cursor: pointer;
    display: inline-block;
    font-family: Roobert, -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    width: 118px;
    height: 45px;
    font-weight: 600;
    outline: none;
    text-align: center;
    text-decoration: none;
    transition: all 300ms cubic-bezier(.23, 1, 0.32, 1);
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    will-change: transform;
  }

  button:disabled {
    pointer-events: none;
  }

  button:hover {
    color: #fff;
    background-color: #1A1A1A;
    box-shadow: rgba(0, 0, 0, 0.25) 0 8px 15px;
    transform: translateY(-2px);
  }

  button:active {
    box-shadow: none;
    transform: translateY(0);
  }
}

// 为评论列表添加动画
@-webkit-keyframes scale-up-ver-bottom {
  0% {
    -webkit-transform: scaleY(0.4);
    transform: scaleY(0.4);
    -webkit-transform-origin: 0% 100%;
    transform-origin: 0% 100%;
  }
  100% {
    -webkit-transform: scaleY(1);
    transform: scaleY(1);
    -webkit-transform-origin: 0% 100%;
    transform-origin: 0% 100%;
  }
}

@keyframes scale-up-ver-bottom {
  0% {
    -webkit-transform: scaleY(0.4);
    transform: scaleY(0.4);
    -webkit-transform-origin: 0% 100%;
    transform-origin: 0% 100%;
  }
  100% {
    -webkit-transform: scaleY(1);
    transform: scaleY(1);
    -webkit-transform-origin: 0% 100%;
    transform-origin: 0% 100%;
  }
}

.scale-up-ver-bottom {
  -webkit-animation: scale-up-ver-bottom 0.4s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
  animation: scale-up-ver-bottom 0.4s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
}
</style>
